package cookie;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 演示如何设置Cookie
 */
public class AddCookieHeader extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String param = req.getParameter("header");
        if (param != null && param.length() > 0)
            addCookieHeader(req, resp);
        else
            addCookie(req, resp);
    }

    /**
     * 通过直接操作 response 头添加 cookie
     */
    public void addCookieHeader(HttpServletRequest req, HttpServletResponse resp) {
        resp.addHeader("Set-Cookie", "aaa=AAA");
        resp.addHeader("Set-Cookie", "bbb=BBB");
    }

    /**
     * 通过便捷方法添加cookie
     */
    public void addCookie(HttpServletRequest req, HttpServletResponse resp) {
        Cookie cookie1 = new Cookie("ccc", "CCC");
        Cookie cookie2 = new Cookie("ddd", "DDD");
        resp.addCookie(cookie1);
        resp.addCookie(cookie2);
    }
}
